package p.ithorns.sample.websocket.core;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.node.ObjectNode;
import p.ithorns.sample.websocket.model.WsMsgType;
import p.ithorns.sample.websocket.model.WsUpMsg;

import java.io.IOException;
import java.util.Optional;

/**
 * WsUpDeserializer
 * <p>
 * 上行数据解析器
 *
 * @author HtL
 * @date 2024/10/15 16:57
 * @since 1.0.0
 */
public class WsUpDeserializer extends StdDeserializer<WsUpMsg<?>> {

    public WsUpDeserializer() {
        this(null);
    }

    protected WsUpDeserializer(Class<?> vc) {
        super(vc);
    }

    @Override
    public  WsUpMsg<?> deserialize(JsonParser p, DeserializationContext ctx) throws IOException {
        ObjectMapper mapper = (ObjectMapper) p.getCodec();

        // 读取整个 JSON 对象
        ObjectNode rootNode = mapper.readTree(p);
        WsUpMsg wsUpMsg = new WsUpMsg<>();

        // 获取 "type" 字段的值
        String type = Optional.ofNullable(rootNode.get("type"))
                .map(JsonNode::asText).orElse(null);
        wsUpMsg.setType(type);

        String clientId = Optional.ofNullable(rootNode.get("clientId"))
                .map(JsonNode::asText).orElse(null);
        wsUpMsg.setClientId(clientId);

        // 根据 "type" 字段确定具体的子类，并进行反序列化
        Class<?> clazz = WsMsgType.getClazz(type);
        if (clazz == null) {
            throw new IOException("Unknown data type: " + type);
        }

        // 获取 "data" 字段
        JsonNode dataNode = rootNode.get("data");
        if (null != dataNode) {
            // 反序列化 "data" 字段
            wsUpMsg.setData(mapper.treeToValue(dataNode, clazz));
        }

        return wsUpMsg;
    }
}